package com.bwie.product.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.*;
import com.bwie.common.domain.request.ProductRequest;
import com.bwie.common.domain.request.ShopRequset;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.TelSmsUtils;
import com.bwie.product.feign.ShopCarFeignController;
import com.bwie.product.service.ProductService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.messaging.MessagingException;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/product")
public class ProductController {
    //注入业务层
    @Autowired
    private ProductService productService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ShopCarFeignController feignController;

    /**
     * 商品列表
     * @param
     * @return
     */
    @GetMapping("showAll")
    public Result showAll(){
        List<ProductRequest> show = productService.showAll();
        return Result.success(show);
    }

    /**
     * 点击关注店铺
     * @param productId
     * @return
     */
    @PostMapping("/shopAttention/{productId}")
    public Result shopAttention(@PathVariable Integer productId) throws MessagingException {
        Integer shop = productService.shopAttention(productId);
        if (shop > 0) {
            //随机生成50元之内红包
            Random rand = new Random();
            int randomNumber = rand.nextInt(50); //生成0~50之间的随机数
            System.out.println("随机红包为："+randomNumber);
            //若生成为10元以内则为满10满减红包
            Result<ShopCar> result = feignController.buyProduct(productId);
            ShopCar data = result.getData();
            //获取登录用户
            String token = request.getHeader("token");
            String userKey = JwtUtils.getUserKey(token);
            String userKey1 = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
            User user = JSONObject.parseObject(userKey1, User.class);
            List<Product> list = productService.findId(productId);
            //给登录用户红包卷
            productService.updPack(randomNumber,user.getUserId());
            //优惠券表
            Coupon coupon = new Coupon();
            //将拥有的优惠券都放在此表内
            coupon.setCouponPacket(randomNumber);
            coupon.setUserId(user.getUserId());
            Integer add = productService.addCoupon(coupon);
            int count=0;
            if (add > 0) {
                //优惠券张数
                count++;
                Systems sys = JSON.parseObject("sys", Systems.class);
                //减去优惠券的数量
                productService.minusCoupon(sys.getSystemId(),sys.getSystemNum(),count);
            }
//            关注成功发送短信
            Map<String, String> map = new HashMap<>();
            map.put("发送短信验证码：消息内容是：【{}】",JSONObject.toJSONString(map));
            TelSmsUtils.sendSms("18171594937",map);
            //MQ发送消息保证消息不丢失
            rabbitTemplate.convertAndSend("sendTel",shop,message -> {
                message.getMessageProperties().setMessageId(UUID.randomUUID().toString());
                return message;
            });
        }
        return Result.success(productId,"关注成功啦");
    }

    /**
     * 加入购物车
     * @param shopRequset
     * @return
     */
    @PostMapping("addCar")
    public Result addCar(@RequestBody ShopRequset shopRequset){
        List<Product> list = productService.findId(shopRequset.getProductId());
        for (Product product : list) {
            shopRequset.setProductId(product.getProductId());
            shopRequset.setShopcarPrice(product.getProductPrice()*shopRequset.getShopcarAmount());
            shopRequset.setProductPrice(product.getProductPrice());
            Integer add = productService.addCar(shopRequset);
        }
        return Result.success(shopRequset,"加入成功");
    }
}
